package com.xm.clj.underserver.controller;

import com.alibaba.fastjson.JSON;
import com.xm.clj.underserver.bean.GetMessage;
import com.xm.clj.underserver.bean.Room;
import com.xm.clj.underserver.utils.DBUtils;
import com.xm.clj.underserver.utils.SendMessage;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "room",urlPatterns = {"/createRoom","/cancelRoom","/findRoom"})
public class RoomController extends HttpServlet {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        InputStream is = req.getInputStream();
        String str = IOUtils.toString(is,"UTF-8");
        String path = req.getServletPath();
        GetMessage message = null;
        if (path.equals("/createRoom")){
            System.out.println("开始创建房间");
            JSONObject jsonObject = JSONObject.fromObject(str);
            Room room = (Room) JSONObject.toBean(jsonObject,Room.class);
            // 生成房间号，记录数据库
            String room_id = DBUtils.createRoom(room);
            if (room_id.length()>0){
                message = new GetMessage("100",room_id);
            }
            else{
                message = new GetMessage("101","error");
            }
        }
        // 查找房间是否存在
        if (path.equals("/findRoom")){
            System.out.println("正在查找房间");
            if (DBUtils.findRoom(str)){
                System.out.println("str  "+str);
                message = new GetMessage("100",str.substring(1,str.length()-1));
            }
            else{
                message = SendMessage.findRoomError;
            }
        }
        resp.getWriter().write(JSON.toJSONString(message));
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);
    }
}
